package com.one.group.admin.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.filter.SaTokenContextFilterForJakartaServlet;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.jwt.StpLogicJwtForStateless;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import com.one.group.enums.ErrorCode;
import com.one.group.exception.BusinessException;
import jakarta.servlet.DispatcherType;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.EnumSet;

/**
 * @author Cherry
 */
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {

    // JWT逻辑实现
    @Bean
    public StpLogic getStpLogicJwt() {
        return new StpLogicJwtForStateless();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SaInterceptor(handle -> {
                    // 自定义校验逻辑
                    try {
                        StpUtil.checkLogin();
                    } catch (NotLoginException e) {
                        throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
                    }
                }))
                .addPathPatterns("/**")
                .excludePathPatterns("/admin/login",
                        "/swagger-ui/**",
                        "/swagger-resources/**",
                        "/v3/api-docs/**",
                        "/v3/api-docs",
                        "/webjars/**",
                        "/doc.html",
                        "/favicon.ico");
    }
    @Bean
    public FilterRegistrationBean<SaTokenContextFilterForJakartaServlet> saTokenContextFilterForJakartaServlet() {
        FilterRegistrationBean<SaTokenContextFilterForJakartaServlet> bean = new FilterRegistrationBean<>(new SaTokenContextFilterForJakartaServlet());
        // 配置 Filter 拦截的 URL 模式
        bean.addUrlPatterns("/*");
        // 设置 Filter 的执行顺序,数值越小越先执行
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        bean.setAsyncSupported(true);
        bean.setDispatcherTypes(EnumSet.of(DispatcherType.ASYNC, DispatcherType.REQUEST));
        return bean;
    }
}
